#include <cmath>
#include "dbpage.h"
#include <QSqlQueryModel>
#include <QSqlRecord>

DbPage::DbPage()
{
    records = 50;
    first = 1;
    previous = 0;
    last = 0;
    total = 0;
    table = "tickets";
    columns = "number,date,customer,phone,ip,status,active";
    orderby = "number asc";
    columnList = columns.split(',');

    connect();
    model = new CustomSqlModel;
}
bool DbPage::isValid()
{
    return (total > 0 && total >= previous && (previous % records == 0));
}
bool DbPage::firstOk()
{
    return (previous >= records) ? true : false;
}
bool DbPage::previousOk()
{
    return (previous >= 2 * records) ? true : false;
}
bool DbPage::nextOk()
{
    return (previous < total - 2 * records) ? true : false;
}
bool DbPage::lastOk()
{
    return (previous < total - records) ? true : false;
}
int DbPage::previousPage()
{
    return previousOk() ? page - 1 : page;
}
int DbPage::nextPage()
{
    return nextOk() ? page + 1 : page;
}
int DbPage::lastPage()
{
    return (int)ceil(total / (records * 1.0f));
}

CustomSqlModel* DbPage::search(QString str, int pag, QString orderBy)
{
    searchText = str;
    if(orderBy!="")
        orderby = orderBy;

    total = searchCount();

    page = lastPage();
    if (pag != 0 && pag < page)
        page = pag;

    previous = (page - 1) * records;
    first = previous + 1;
    last = previous + records;
    if (last > total)
        last = total;
    //model = null;
    if (isValid())
        model = search();
    return model;
}

CustomSqlModel* DbPage::search()
{
    sql = createSql();
    model->setQuery(sql);
    return model;
}
int DbPage::searchCount()
{
    sql = "select count(*) as total from " + table;
    whereSql = "";
    if(searchText != "")
    {
        whereSql = " where "+columnList[0]+" like '%"+ searchText +"%'";
        for(int i=1;i<columnList.count()-1; i++)
            whereSql += " or "+ columnList[i] +" like '%"+ searchText +"%'";
        sql += whereSql;
    }
    model->setQuery(sql);
    return model->record(0).value("total").toInt();
}
QString DbPage::createSql()
{
    sql = "select "+columns+" from "+table;
    if(searchText!=QString::null)
        sql += whereSql;
    sql += " order by "+orderby;
    sql += " limit "+ QString::number(previous) +","+QString::number(records);
    return sql;
}
void DbPage::connect()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("tickets");
    db.setUserName("root");
    db.setPassword("");
    db.open();
}
